// Package logger defines gorm logger
package logger

import (
	"fmt"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"os"
	"strings"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var SugarLogger *zap.SugaredLogger
var Logger *zap.Logger
var _logPath string

func InitLogger(logPath string) {
	_logPath = logPath
	writeSyncer := getLogWriter()
	//writeSyncerErr := getErrLogWriter()
	encoder := getEncoder()
	c1 := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	//c2 := zapcore.NewCore(encoder, writeSyncerErr, zap.ErrorLevel)
	// 使用NewTee将c1和c2合并到core
	core := zapcore.NewTee(c1)
	Logger = zap.New(core, zap.AddCaller())
	SugarLogger = Logger.Sugar()
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}

// 记录全量日志
func getLogWriter() zapcore.WriteSyncer {
	filename := fmt.Sprintf("%s/fx_swift_api.log", strings.Trim(_logPath, "/"))
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    10,
		MaxBackups: 50,
		MaxAge:     30,
		Compress:   false,
	}
	ws := io.MultiWriter(lumberJackLogger, os.Stdout) //将日志同时输出到文件和终端。
	return zapcore.AddSync(ws)
}

// 记录ERROR级别的日志
func getErrLogWriter() zapcore.WriteSyncer {
	filename := fmt.Sprintf("%s/fx_swift_api.err.log", strings.Trim(_logPath, "/"))
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    10,
		MaxBackups: 50,
		MaxAge:     30,
		Compress:   false,
	}
	ws := io.MultiWriter(lumberJackLogger, os.Stdout) //将日志同时输出到文件和终端。
	return zapcore.AddSync(ws)
}
